package com.jet.chat.command;

import java.util.regex.Matcher;

import com.jet.chat.dbquery.ChatQueryGetHistory;
import com.jet.chat.dbquery.ChatQueryGetHistoryParams;
import com.jet.chat.dbquery.ChatQueryGetHistoryResult;
import com.jet.chat.dbquery.ChatQueryGetHistoryResultRaw;
import com.jet.chat.message.Message;
import com.jet.chat.server.ChatServer;
import com.jet.chat.server.ChatSession;


public class ChatCommandViewHistory extends ChatCommandAbstract {
	public ChatCommandViewHistory() {
		super("^/\\w+\\s([\\w\\.-]+)$");
	}

	@Override
	protected void executeCommand(Matcher matcher, ChatServer chatServer, ChatSession chatSession, Message chatMessage) throws Exception {
		String responce = "";
		String timestamp = matcher.group(1);
		ChatQueryGetHistoryResult result = (ChatQueryGetHistoryResult) new ChatQueryGetHistory().execute(chatServer.getDBConnectionService(), new ChatQueryGetHistoryParams(chatSession.getUserId(), timestamp));
		String line;
		for (ChatQueryGetHistoryResultRaw raw : result.getResult()) {
			if (raw.getPub() == 0) {
				line = raw.getTimestamp() + "\t" + raw.getUsername() + " whispers: " + raw.getContent() + "\r\n";
			} else {
				line = raw.getTimestamp() + "\t" + raw.getChannelName() + " : " + raw.getUsername() + " > " + raw.getContent() + "\r\n";
			}
			responce = responce + line;
		}
		chatSession.getQueue().addMessage(responce);
	}

}
